<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 输入框搜索框 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <!-- 搜索框 -->
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入"
            class="input-with-select"
            clearable
            @clear="getUserList">
            <el-button @click="getUserList" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <!-- 添加按钮 -->
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch @change="userStateChange(scope.row)" v-model="scope.row.mg_state"></el-switch>
          </template>
        </el-table-column>
        <!-- 三个按钮区域 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top-start"
              :enterable="false"
            >
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top-start"
              :enterable="false"
            >
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" @click="setRole(scope.row)" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 页码区域 -->
      <el-pagination
        @size-change="hanndleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5,10]"
        :page-size="queryInfo.pagesize"
        background
        layout="total,sizes,prev,pager,next,jumper"
        :total="total"></el-pagination>
    </el-card>




    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="30%" @close="addDialogClosed">
      <!-- 内容主体区 -->
      <el-form :model="addFrom" :rules="addFromRules" ref="addFromRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addFrom.username"></el-input>
        </el-form-item>
    
        <el-form-item label="密码" prop="password">
          <el-input v-model="addFrom.password"></el-input>
        </el-form-item>
      
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFrom.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息的对话框 -->
    <el-dialog title="修改用户信息" :visible.sync="editDialog" width="50%" @close="editDialogClose">

      <el-form :model="editFrom" :rules="editFromRules" ref="editFromRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClose">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"><!--正真记录的值-->
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "users",
  data() {
    //添加用户的表单预验证 自定义验证
    var checkEamil = (rule,value,cb) => {
      const regEamil = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
                      
      if(regEamil.test(value)){
        return cb()
      }

      cb(new Error('请输入合法的邮箱'))
    }
    var checkMobile = (rule,value,cb) => {
      const regMobile = /^[1]([3-9])[0-9]{9}$/
      // /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
      if(regMobile.test(value)){
        return cb()
      }

      cb(new Error('请输入合法的手机号'))
    }
    return {
      //获取用户列表的参数对象
      queryInfo: {
        query: "", //查询参数
        pagenum: 1, //当前页码
        pagesize: 5 //每条显示条数
      },

      //get到的用户数据
      userList: [],

      total: 0, //总页码


      //控制添加用户对话框显示隐藏
      addDialogVisible: false,
      //添加用户的表单数据
      addFrom: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //添加用户的表单预验证
      addFromRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "请输入3到10字符之间的用户名！", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "请输入6到15字符之间的密码！", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEamil ,trigger:"blur"}
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile ,trigger:"blur"}
        ],
      },


      //控制修改用户对话框显示隐藏
      editDialog:false,
      //根据用户id查到的用户表单
      editFrom:{},
      //校验规则
      editFromRules:{
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEamil ,trigger:"blur"}
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile ,trigger:"blur"}
        ],
      },


      //控制分配角色对话框显示隐藏
      setRoleDialogVisible:false,
      //需要被分配角色的用户信息
      userInfo:{},
      //角色列表
      rolesList:[],
      //已经选中的角色id值
      selectedRoleId:''
    };
  },
  methods: {
    //获取用户数据列表
    async getUserList() {
      var { data: res } = await this.$axios.get("users", {
        params: this.queryInfo
      });

      if (res.meta.status != 200) {
        this.$message.error("请求用户数据失败！");
        return;
      }

      this.userList = res.data.users;
      this.total = res.data.total;
      console.log("从后台获取了数据",res)
    },

    //监听页码改变
    hanndleSizeChange(newSize) {
      //大页码
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newCurrent) {
      //小页码
      this.queryInfo.pagenum = newCurrent;
      this.getUserList();
    },

    //监听switch开关状态改变
    async userStateChange(userInfo) {
      const { data: res } = await this.$axios.put(
        `users/${userInfo.id}/state/${userInfo.mg_state}`
      );

      if (res.meta.status != 200) {
        userInfo.mg_state = !userInfo.mg_state;
        this.$message.error("更新失败");
        return;
      }

      this.$message.success("更新成功");
      console.log("发送了请求改变状态",res)
    },


    //监听添加用户弹出框的关闭
    addDialogClosed(){
      this.$refs.addFromRef.resetFields();
    },
    //点击添加用户按钮
    addUser(){
      this.$refs.addFromRef.validate( async vaild => {
        if(!vaild){
          return
        }
        //成功就发请求
        const {data:res} = await this.$axios.post('users',this.addFrom)
        if(res.meta.status != 201){
          this.$message.error('添加失败！');
        }
        this.$message.success('添加成功');
        console.log("添加了成员",res)
        // 关闭对话框
        this.addDialogVisible = false;
        //重新获取列表数据
        this.getUserList();
      })
    },


    //展示要修改的用户数据
    async showEditDialog(id){
      console.log(id)
      this.editDialog = true;
      const {data:res} = await this.$axios.get("users/"+ id);
      if(res.meta.status != 200){
        this.editDialog = false;
        this.$message.error('修改请求失败!');
        return;
      }

      this.editFrom = res.data;

    },
    //修改用户重新验证
    editDialogClose(){
      this.$refs.editFromRef.resetFields()
    },
    //修改用户预验证和验证成功修改
    editUserInfo(){
      this.$refs.editFromRef.validate( async vaild => {
        if(vaild){
          this.editDialog = false;
          const {data:res} = await this.$axios.put("users/"+ this.editFrom.id,{
            email:this.editFrom.email,
            mobile:this.editFrom.mobile,
          })
          if(res.meta.status != 200){
            this.$message.error('修改请求错误！')
            return;
          }
          // 关闭对话框
          this.editDialog = false;
          // 刷新数据列表
          this.getUserList();

          this.$message.success('修改用户数据成功！');
          return;
        }

        this.$message.error('预验证失败')
        return;
      })
    },


    //根据id删除用户
    async removeUserById(id){
        const ret = await this.$confirm('是否永久删除该用户？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        //取消删除返回值为cancel，确认返回值为confirm
        console.log(ret)
        if(ret == "confirm"){
          const {data:res} = await this.$axios.delete('users/' + id);
          if(res.meta.status == 200){
            this.$message.success('删除成功!');
            this.getUserList();
            return;
          }
          this.$message.error('删除失败');
          this.$notify({
            title: '警告',
            message: res.meta.msg,
            type: 'warning'
          });
          return;
        }
        this.$message.info('取消删除!')
    },
    //get所有的角色列表
    async getRolesList() {
      var { data: res } = await this.$axios.get("roles");
      if (res.meta.status != 200) {
        this.$message.error("获取角色列表失败");
        return;
      }
      this.rolesList = res.data;
    },
    //分配角色的对话框显示
    setRole(row){

      // 在展示前获取所有的角色列表
      this.getRolesList();

      this.setRoleDialogVisible = true
      this.userInfo = row;
    },
    //确定分配时
    async saveRoleInfo(){
      if(!this.selectedRoleId){
        this.setRoleDialogVisible = false
        this.$message('未修改')
        return;
      }
      const {data:res} = await this.$axios.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId})
      if(res.meta.status != 200){
        this.$message.error('修改失败');
        return
      }

      this.$message.success('修改成功');
      this.setRoleDialogVisible = false;
      this.getUserList();
    },
    //分配对话框关闭时清空已选择的
    setRoleDialogClose(){
      this.selectedRoleId = "";
      this.userInfo = "";
    }
  },
  created() {
    //用户数据列表
    this.getUserList();
  }
};
</script>

<style lang="less" scoped>
</style>